<?php
/**
 * Created by PhpStorm.
 * User: 我想有个家
 * Date: 2020/3/27
 * Time: 13:01
 */

namespace App\Controller\v1;


use App\Controller\Base;
use App\Model\User;
use App\Service\OssService;
use App\Service\SmsService;
use App\Validate\UserValidate;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;

/**
 * @Controller(prefix="v1")
 * Class Index
 * @package App\Controller\user
 */
class UserController extends Base {
    /**
     * 获取用户信息
     * @Middleware(\App\Middleware\MustMiddleware::class)
     * @RequestMapping(path="user_info",methods="get")
     * @return array
     */
    public function getInfo() {
        $uid = $this->request->getAttribute('uid');
        /**@var User $user */
        $user = User::query()
            ->where('id', $uid)
            ->select('id', 'mobile', 'nick_name', 'headimg', 'create_time')
            ->first();
        $user->oss('headimg');
        return success($user->toArray());
    }

    /**
     * 更新用户信息
     * @Middleware(\App\Middleware\MustMiddleware::class)
     * @RequestMapping(path="user_info",methods="put")
     * @return array
     */
    public function putInfo() {
        $validate = $this->di->get(UserValidate::class);
        $validate->check($validate->changeInfo());
        $uid = $this->request->getAttribute('uid');
        $param = [
            'nick_name' => filterEmoji($this->body('nick_name')),
            'headimg' => $this->body('headimg'),
            'mobile' => $this->body('mobile'),
            'sms_code' => $this->body('sms_code'),
        ];
        /**
         * @var $user User
         */
        $user = User::query()->where('id', $uid)
            ->select('nick_name', 'headimg')
            ->first();
        if (empty($user)) {
            return error('用户不存在');
        }
        $oldimg = $user->headimg;
        if ($param['nick_name']) {
            $user->nick_name = $param['nick_name'];
        }
        if ($param['headimg']) {
            $user->headimg = $param['headimg'];
        }
        if ($param['mobile']) {
            if ($this->di->get(SmsService::class)->verify($param['mobile'], $param['sms_code'])) {
                return error('短信验证码错误');
            }
            // 判断手机号码是否注册过
            if (User::mobileUsed($param['mobile'])) {
                return error('手机号已经注册');
            }
            $user->mobile = $param['mobile'];
        }
        if ($user->save()) {
            // 删除旧的头像
            $oldimg && $this->di->get(OssService::class)->delete($oldimg);
            return success($user->toArray());
        } else {
            return error('更新失败');
        }
    }
}
